<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .seasonBox{
            display: flex;
            padding: 4px;
        }
        .seasonFont{
            width: 50px;
            padding: 2px;
            text-align: center;
            background-color: rgb(173, 115, 6);
            color: #fff;
        }
        .seasonCard{
            flex-grow: 1;
            display: flex;
            align-items: center;
        }
        .plant{
            padding: 2px 4px;
            cursor: pointer;
        }
        .plantData{
            position: absolute;
            padding: 2px;
            box-sizing: border-box;
            border-radius: 4px;
            box-shadow: 0 0 5px rgb(177, 105, 87);
        }
        .pinfo{
            font-size: 13px;
            background-color: #fff;
            padding: 2px;
        }
        .pinfo>div{
            text-align: center;
        }
        .analysisContainer{
            display: flex;
        }
        .plant9{
            min-width: 150px;
            width: 150px;
            height: 150px;
            display: flex;
            flex-wrap: wrap;
            align-items:stretch;
        }
        
        .plant9item{
            box-sizing: border-box;
            width: 50px;
            height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
            box-shadow: 0 0 5px rgb(177, 105, 87);
            overflow: hidden;
            font-size: 13px;
            cursor: pointer;
        }
        .desContainer{
            padding: 2px 4px;
            overflow: auto;
        }
        .desContainer::-webkit-scrollbar {
            background-color: rgba(#000, 0.1);
        }
        .desContainer::-webkit-scrollbar-thumb {
            background-color: rgba(#ffb24e, 0.8);
        }
        .des{
            font-size: 13px;
            padding: 3px;
            cursor: pointer;
            color: #333;
        }
        .btn{
            margin-left: 4px;
            cursor: pointer;
            padding: 2px 4px;
            font-size: 12px;
            border-radius: 2px;
            box-sizing: border-box;
            border: 0;
            box-shadow: 0 0 2px #333;
        }
        .bg1{
            background-color: rgb(158, 125, 36);
            color: #fff;
        }
        .bg2{
            background-color: rgb(118, 218, 25);
            color: #fff;
        }
        .bg3{
            background-color: rgb(187, 92, 37);
            color: #fff;
        }
        .bg4{
            background-color: rgb(47, 130, 226);
            color: #fff;
        }
        .auto{
            display: flex;
            flex-wrap: wrap;
        }
        .autoItem{
            cursor: pointer;
            margin: 4px 6px 0 0;
            padding: 2px;
            font-size: 13px;
            box-sizing: border-box;
            box-shadow: 0 0 2px #333;
        }
        .autoItem:hover{
            transition: background-color 200ms;
            background-color: #09f;
            color: #fff;
        }
        .filter{
            position: relative;
            /* display: flex;
            flex-wrap: wrap; */
        }
        .filter_plant{
            position: relative;
            float: left;
            font-size: 12px;
            padding: 2px 4px;
            margin-left: 4px;
            margin-top: 4px;
            cursor: pointer;
            box-sizing: border-box;
            box-shadow: 0 0 2px #333;
        }
        .selected {
            background-color: #09f;
            color: #fff;
        }
        .flex{
            display: flex;
        }
        .ipt{
            width: 30px;
        }
    </style>
</head>
<body>

    <div id="root">
        <div class="seasonContainer">
            
        </div>
        <div class="analysisContainer">
            <div class="plant9">
                <div class="plant9item"></div><div class="plant9item"></div><div class="plant9item"></div>
                <div class="plant9item"></div><div class="plant9item"></div><div class="plant9item"></div>
                <div class="plant9item"></div><div class="plant9item"></div><div class="plant9item"></div>
            </div>
            <div class="desContainer">
                <div class="des">需求</div>
                <div> 
                    <button id="clearBtn" class="btn">清空</button>&nbsp;
                    <button id="btn1" class="btn bg1">分析:春</button>&nbsp;
                    <button id="btn2" class="btn bg2">分析:夏</button>&nbsp;
                    <button id="btn3" class="btn bg3">分析:秋</button>&nbsp;
                    <button id="btn4" class="btn bg4">分析:冬</button>
                    <div>
                        会根据选择的季节和已经选择的作物，对剩余位置分析推荐, 作物分析时分析的作物种类越多，分析越慢
                    </div>
                </div>
                <div>
                    <span>作物过滤:分析时不去分析一些作物来提升速度</span>
                    <div id="filter" class="filter"></div>
                </div>
            </div>
        </div>
        <div class="flex">
            初始耕地资源: 
            营养<input class="ipt" id="fat1" value="0"></input> 
            堆肥<input class="ipt" id="fat2" value="0"></input> 
            粪肥<input class="ipt" id="fat3" value="0"></input> 
            水<input class="ipt" id="water" value="0"></input>
        </div>
        <div class="auto">自动推荐</div>
    </div>
    <div class="plantData"></div>
    <script>
        let useWater = [0.45,1.2,2.1]
        let tianKeng = 9;
        document.querySelector(".des").addEventListener("click", e => {
            if(tianKeng == 9) {
                tianKeng = 10
            } else {
                tianKeng = 9
            }
            alert(`配置改为${tianKeng}坑田`);
        });
        let baseResource = {water:0, fat1:0, fat2:0, fat3:0};
        document.querySelector("#fat1").addEventListener("change", e => {
            let value = e.target.value.trim();
            if(/^\d+\.?\d*$/.test(value)) {
                baseResource.fat1 = value - 0;
            }
        });
        document.querySelector("#fat2").addEventListener("change", e => {
            let value = e.target.value.trim();
            if(/^\d+\.?\d*$/.test(value)) {
                baseResource.fat2 = value - 0;
            }
        });
        document.querySelector("#fat3").addEventListener("change", e => {
            let value = e.target.value.trim();
            if(/^\d+\.?\d*$/.test(value)) {
                baseResource.fat3 = value - 0;
            }
        });
        document.querySelector("#water").addEventListener("change", e => {
            let value = e.target.value.trim();
            if(/^\d+\.?\d*$/.test(value)) {
                baseResource.water = value - 0;
            }
        });
        let PLANTS = {
            suan: {
                name:"大蒜",
                spring: true,
                xia: true,
                qiu: true,
                winter: true,
                fat: [2, -4, 2],
                seed:"种子荚",
                water: -1,
            },
            fanqie: {
                name:"番茄",
                spring: true,
                xia: true,
                qiu: true,
                fat: [-1, -1, 2],
                seed:"带刺种子",
                water: -3,

            },
            yumi: { // 25
                name:"玉米",
                spring: true,
                xia: true,
                qiu: true,
                fat: [1, 2, -1],
                seed:"蔟状种子",
                water: -1,

            },
            yangcong: {
                name:"洋葱",
                spring: true,
                xia: true,
                qiu: true,
                fat: [-4, 2, 2],
                seed:"尖形种子",
                water: -2,

            },
            luobo: {
                name:"胡萝卜",
                spring: true,
                qiu: true,
                winter: true,
                fat: [-2, 1, 1],
                seed:"椭圆形种子",
                water: -1,

            },
            potato: {  // 12.5   25
                name:"土豆",
                spring: true,
                qiu: true,
                winter: true,
                fat: [1, 1, -2],
                seed:"毛茸茸的种子",
                water: -1,

            },
            firelongguo: {  // 9.5  20
                name:"火龙果",
                spring: true,
                xia: true,
                fat: [2, 2, -4],
                seed:"球茎状种子",
                water: -2,

            },
            shiliu: {
                name:"石榴",
                spring: true,
                xia: true,
                fat: [-4, 2, 2],
                seed:"风刮来的种子",
                water: -2,

            },
            watergua: {
                name:"西瓜",
                unselect: true,
                spring: true,
                xia: true,
                fat: [2, -1, -1],
                seed:"方形种子",
                water: -3,

            },
            qiezi: { // 25
                name:"茄子",
                unselect: true,
                spring: true,
                qiu: true,
                fat: [1, 1, -2],
                seed:"漩涡种子",
                water: -2,

            },
            luhui: {
                name:"芦荟",
                unselect: true,
                spring: true,
                winter: true,
                fat: [1, -2, 1],
                seed:"筒状种子",
                water: -1,

            },
            lajiao: {
                name:"辣椒",
                xia: true,
                qiu: true,
                fat: [2, 2, -4],
                seed:"块状种子",
                water: -1,

            },
            nangua: { // 37.5  沃特49
                name:"南瓜",
                qiu: true,
                winter: true,
                fat: [-2, 1, 1],
                seed:"尖种子",
                water: -2,

            },
            liulian: {  // 25   沃特48
                name:"榴莲",
                spring: true,
                fat: [2, -4, 2],
                seed:"脆籽荚",
                water: -1,
            }
        };

        
        let spring = [];
        let xia = [];
        let qiu = [];
        let winter = [];

        let plantKeys = []
        for (let key in PLANTS) {
            PLANTS[key].fat = PLANTS[key].fat.map(v => v*8.3333333333333333333)
            plantKeys.push({key, select: PLANTS[key].unselect? false:true});
            if(PLANTS[key].spring){ spring.push(key) }
            if(PLANTS[key].xia){ xia.push(key) }
            if(PLANTS[key].qiu){ qiu.push(key) }
            if(PLANTS[key].winter){ winter.push(key) }
        }

        document.querySelector("#filter").innerHTML = plantKeys.map((item, i) => {
            return `<div data-key="${item.key}" data-i="${i}" class="${item.select? "filter_plant selected" : "filter_plant"}">${PLANTS[item.key].name}(${PLANTS[item.key].seed})</div>`
        }).join("\n")

        let plantEls = document.querySelectorAll(".filter_plant");
        plantEls.forEach(el => {
            el.addEventListener("click", e => {
                let key = e.target.dataset.key;
                let i = e.target.dataset.i;
                plantKeys[i].select = !plantKeys[i].select;
                e.target.classList.toggle('selected')
            });
        })
        let seasonContainer = document.querySelector(".seasonContainer");
        seasonContainer.innerHTML = renderSeason({season:"春", plants:spring})+renderSeason({season:"夏", plants:xia})+renderSeason({season:"秋", plants:qiu})+renderSeason({season:"冬", plants:winter})

        let plantsDiv = document.querySelectorAll(".plant");
        
        let plant9 = [];
        
        plantsDiv.forEach(el => {
            el.addEventListener("mouseenter", e=> {
                let hoverel = document.querySelector(".plantData");
                hoverel.style.left = e.clientX+"px";
                hoverel.style.top = e.clientY+"px";
                let k = e.target.dataset.key;
                let pInfo = PLANTS[k];
                let seaonStr = [];
                if(pInfo.spring){ seaonStr.push("春")}
                if(pInfo.xia){ seaonStr.push("夏")}
                if(pInfo.qiu){ seaonStr.push("秋")}
                if(pInfo.winter){ seaonStr.push("冬")}
                hoverel.innerHTML = `<div class="pinfo">
                    <div>季节：${seaonStr.join(" ")}</div>
                    <div>水需求：${-pInfo.water}</div>
                    <div>肥料变动</div>
                    <div>营养${pInfo.fat[0]} 堆肥${pInfo.fat[1]} 粪肥${pInfo.fat[2]}</div>
                </div>`
            });
            el.addEventListener("mouseleave", e=> {
                let hoverel = document.querySelector(".plantData");
                hoverel.innerHTML = ``
            });
            el.addEventListener("click", e=> {
                let k = e.target.dataset.key;
                plant9=plant9.filter(v => PLANTS[v]);
                if(plant9.length < 9) { plant9.push(k); render9() }
            });
        });

        document.querySelector("#clearBtn").addEventListener("click", e => {
            plant9 = [];
            render9();
        });
        document.querySelector("#btn1").addEventListener("click", e => {
            document.querySelector(".auto").innerHTML = "分析中，如果对应季节作物种类太多，分析时间会比较长";
            setTimeout(() => {
                let data = analysisPlanta({
                    plants: plant9.filter(v => PLANTS[v]),
                    pei: [], 
                    seaon: "spring",
                    k: tianKeng
                });
                renderAuto(data);
            }, 200);
        });
        document.querySelector("#btn2").addEventListener("click", e => {
            document.querySelector(".auto").innerHTML = "分析中，如果对应季节作物种类太多，分析时间会比较长";
            setTimeout(() => {
                let data = analysisPlanta({
                    plants: plant9.filter(v => PLANTS[v]),
                    pei: [], 
                    seaon: "xia",
                    k: tianKeng
                });
                renderAuto(data);
            }, 200);
        });
        document.querySelector("#btn3").addEventListener("click", e => {
            document.querySelector(".auto").innerHTML = "分析中，如果对应季节作物种类太多，分析时间会比较长";
            setTimeout(() => {
                let data = analysisPlanta({
                    plants: plant9.filter(v => PLANTS[v]),
                    pei: [], 
                    seaon: "qiu",
                    k: tianKeng
                });
                renderAuto(data);
            }, 200);
        });
        document.querySelector("#btn4").addEventListener("click", e => {
            document.querySelector(".auto").innerHTML = "分析中，如果对应季节作物种类太多，分析时间会比较长";
            setTimeout(() => {
                let data = analysisPlanta({
                    plants: plant9.filter(v => PLANTS[v]),
                    pei: [], 
                    seaon: "winter",
                    k: tianKeng
                });
                renderAuto(data);
            }, 200);
        });
        
        function renderAuto(data) {
            if(data && data.length && data.length > 0) {
                if(data.length > 100) {
                    data = data.slice(0, 100)
                }
                let html = data.map(v => {
                    let peizhi = "";
                    let data_plants = [];
                    for (let key in v) {
                        if(PLANTS[key] && v[key] > 0) {
                            peizhi += `${PLANTS[key].name}:${v[key]} `;
                            for (let i = 0; i < v[key]; i++) {
                                data_plants.push(key)
                            }

                        }
                    }
                    return `<div class="autoItem" data-plants="${data_plants.join(",")}">${peizhi}</div>`
                }).join("\n");
                document.querySelector(".auto").innerHTML = html;
                let autoItems = document.querySelectorAll(".autoItem");
                autoItems.forEach(el => {
                    el.addEventListener("click", e=> {
                        let data = e.target.dataset.plants;
                        plant9 = data.split(",");
                        render9()
                    })
                })
            } else {
                document.querySelector(".auto").innerHTML = "分析作物种类超过了7种,排列组合太多，利用过滤减少分析种类";
            }
        }


        function render9() {
            if(plant9.length < 9) {
                plant9.length = 9
                for (let index = 0; index < plant9.length; index++) {
                    if(!plant9[index]){plant9[index] = ""}
                }
            }
            let html = plant9.map((v, i) => {
                return `<div class="plant9item" data-id="${i}">${PLANTS[v]?.name || " "}</div>`
            }).join("\n");
            document.querySelector(".plant9").innerHTML = html;
            document.querySelectorAll(".plant9item").forEach(el=>{
                el.addEventListener("click", e=>{
                    let id = e.target.dataset.id;
                    plant9[id] = " ";
                    render9();
                });
            });
            let ret = calcFarm({ // 
                plants: plant9.filter(v => PLANTS[v]),
                ...baseResource
            })
            document.querySelector(".des").innerHTML = `需求:营养:${ret.fat1.toFixed(2)} 堆肥:${ret.fat2.toFixed(2)} 粪肥:${ret.fat3.toFixed(2)} 水分:${-ret.water}`;
            
        }

        function renderSeason(props) {
            let {season, plants} = props
            let html = `<div class="seasonBox">
                <div class="seasonFont">${season}</div>
                <div class="seasonCard">
                    ${plants.map(v => {
                        return `<div class="plant" data-key="${v}">${PLANTS[v].name}</div>`
                    }).join("\n")}    
                </div>
            </div>`;
            return html
        }


        function analysisPlanta(props) { // 杂项配对 不考虑巨大化 考虑季节
            let {plants, seaon, pei, k} = props;
            if(plants.length < 9) {
                let plantsCount = {}
                plants.forEach(v => plantsCount[v] = (plantsCount[v]||0)+1)

                let usePlats;
                if(seaon) {
                    usePlats = Object.keys(PLANTS).filter(v => PLANTS[v][seaon] && plantKeys.find(item=>item.select&&item.key==v)) // PLANTS[v][seaon] &&
                } else {
                    usePlats = Object.keys(PLANTS).filter(v => pei.includes(v)) // PLANTS[v][seaon] &&
                }
                let plantInfos = {}
                usePlats.forEach(v => plantInfos[v] = 0)
                plants.forEach(v => plantInfos[v] = (plantInfos[v] || 0) + 1)
                let comb = [];
                if(plants.length == k-1) {
                    for (let key2 in plantInfos) {
                        let pinfo = JSON.parse(JSON.stringify(plantInfos))
                        pinfo[key2]++;
                        comb.push(pinfo)
                    }
                } else if (plants.length == k-2) {
                    for (let key2 in plantInfos) {
                        let pinfo = JSON.parse(JSON.stringify(plantInfos))
                        pinfo[key2]++;
                        for (let key3 in plantInfos) {
                            let pinfo2 = JSON.parse(JSON.stringify(pinfo))
                            pinfo2[key3]++;
                            comb.push(pinfo2)
                        }
                    }
                } else {
                    let kinds = Object.keys(plantInfos).length;
                    if(kinds > 7) {
                        return
                    }
                    comb = getCombination(plantInfos, k)
                }
                comb = comb.map(v => { 
                    let plist = [];
                    for (let key in v) {
                        if(v[key] > 0) {
                            for (let i = 0; i < v[key]; i++) {
                                plist.push(key)
                            }
                        }
                    }
                    v.data = calcFarm({plants:plist,...baseResource});  
                    return v;
                });
                comb.sort((b, a) => {return (fatPoint(a.data) - fatPoint(b.data)|| judahuia(a)-judahuia(b) ||a.data.water-b.data.water)})
                return comb
            }
        }


        function calcFarm(props) {
            let {plants, seaon} = props
            plants = plants.filter(v => PLANTS[v]);
            let water = 0;
            let fat1 = props.fat1 || 0;
            let fat2 = props.fat2 || 0;
            let fat3 = props.fat3 || 0;
            plants.forEach(item => {
                let plantINfo = PLANTS[item];
                let waterUse = ((-plantINfo.water)-1);
                water += useWater[waterUse] * 20;
                fat1 += plantINfo.fat[0];
                fat2 += plantINfo.fat[1];
                fat3 += plantINfo.fat[2];
            })
            fat1 = fat1.toFixed(5)-0;
            fat2 = fat2.toFixed(5)-0;
            fat3 = fat3.toFixed(5)-0;
            return {
                water, fat1, fat2, fat3
            }
        }





        function getCombination (obj, max) {
            let arr = Array(max + 1).fill().map((_,i)=>i);
            let entrys = Object.entries(obj)
            let num = entrys.length;
            let value = max - Object.values(obj).reduce((a,b) => a + b)
            var r = [];
            (function f(t, a, n) {
                if (n === 0) {
                    if(t.reduce((a1,b1) => a1+b1) !== value){return}
                    let ret = {}
                    for (let i in t) {
                        ret[entrys[i][0]] = t[i]
                    }
                    for (let key in obj) {
                        ret[key] = (ret[key] || 0) + obj[key]
                    }
                    r.push(ret)
                    return ;
                }
                for (var i = 0, l = a.length; i < l; i++) {
                    f(t.concat(a[i]), a, n - 1);
                }
            })([], arr, num);
            return r;
        }

        function judahuia(props) {
            let point = 0;
            for (let key in props) {
                if(/number/.test(typeof props[key])){
                    if(props[key] >= 2){
                        point++;
                    }
                }
            }
            return point
        }

        function fatPoint(data) {
            let {fat1, fat2, fat3, water} = data;
            let point = 0;
            if(water <= 120) {point += 10}
            if(fat1 < 0) { point += fat1/10 }
            if(fat2 < 0) { point += fat2/10 }
            if(fat3 < 0) { point += fat3/10 }
            return point
        }
    </script>
</body>
</html>